package com.turing.pre.processor.service;

import com.turing.pre.processor.file.processor.PDFProcessor;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

@Component
public class TaskThread {

    private static final Logger logger = LoggerFactory.getLogger(TaskThread.class);

    private String sep = File.separator;

    public void excutVoidTask(File filePath, String targetPath) {

        PDFProcessor.pdf2png(filePath, targetPath);

    }

    public Future<String> excuteValueTask(String filePath, String textPackages, String tablePackages, String substringName) {

        //获取文本
        String page = filePath.substring(filePath.lastIndexOf("_") + 1, filePath.lastIndexOf("."));
        PDFProcessor.getPdfLocationByPage(filePath, textPackages + sep + substringName + "_" + page + ".json");
        //获取表格
        PDFProcessor.getPdfLocationByTable(filePath, tablePackages + sep + substringName + "_" + page + ".json");

        return new AsyncResult<String>(filePath);
    }


    public static final String PNG_SUFFIX = ".jpg";

    @Async
    public void doImage(String targetPath, File file, int i, CountDownLatch countDownLatch) {

        try (PDDocument doc = PDDocument.load(file);) {

            PDFRenderer renderer = new PDFRenderer(doc);
            BufferedImage image = renderer.renderImageWithDPI(i, 72); // Windows native DPI
            File imageFile = new File(targetPath + "_" + i + PNG_SUFFIX);
            if (!imageFile.exists()) {
                imageFile.mkdirs();
            }
            ImageIO.write(image, "jpg", imageFile);
            image.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();//执行完线程数量-1
        }

    }
}